<?php

namespace App\Http\Controllers\Root;
use App\Http\Controllers\Controller;
use App\Http\Requests\ContactRequest;
use App\Repositories\ContactRepository;
use Illuminate\Http\Request;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

class ContactController extends Controller
{
    /** @var  ContactRepository */
    private $contactRepository;

    public function __construct(ContactRepository $contactRepo)
    {
        $this->contactRepository = $contactRepo;
    }

    /**
     * Display a listing of the Contact.
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $where = [];
        $order_by = [];
        $result = [];
        $this->contactRepository->pushCriteria(new RequestCriteria($request));
        $result = $this->contactRepository->getResult(15, $where, $order_by);
        return $this->r_view('root.contacts.index', ['contacts' => $result]);
    }


    /**
     * Store a newly created Contact in storage.
     *
     * @param ContactRequest $request
     *
     * @return Response
     */
    public function store(ContactRequest $request)
    {
        $input = $request->all();
        if ($input['fb-id'] != 0) {
            $result = $this->contactRepository->findWithoutFail($input['fb-id']);
            if (empty($result)) {
                return $this->sendError('记录已删除');
            }
            $this->contactRepository->update($input, $input['fb-id']);
            return $this->sendResponse(1, '更新成功');
        } else {
            $this->contactRepository->create($input);
            return $this->sendResponse(1, '添加成功');
        }
    }

    /**
     * Display the specified Contact.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $contact = $this->contactRepository->findWithoutFail($id);

        if (empty($contact)) {
            return redirect(route('contacts.index'));
        }

        return $this->r_view('root.contacts.show')->with('contact', $contact);
    }

    /**
     * Show the form for editing the specified Contact.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $contact = $this->contactRepository->findWithoutFail($id);

        if (empty($contact)) {
            return redirect(route('contacts.index'));
        }

        return $this->r_view('root.contacts.edit')->with('contact', $contact);
    }


    /**
     * Remove the specified Contact from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        $contact = $this->contactRepository->findWithoutFail($id);
        if (empty($contact)) {
            return $this->sendError('该记录已删除');
        }
        $this->contactRepository->delete($id);
        return $this->sendResponse(1, '删除成功');
    }
}
